package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.ExtensionDao;
import cn.yunyichina.provider.bone.entity.Extension;
import cn.yunyichina.provider.bone.utils.BoneMsgUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.BoneService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.PersonalUserOpenid;
import cn.yunyichina.provider.iface.entity.base.OrgUserOpenidVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 15-AK on 2017/5/16.
 */
@Service
public class BoneMsgServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(BoneMsgServiceImpl.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final String CANCEL_OPERATION_TEMPLATECODE = "IMG22012";
    private final String CANCEL_INQUIRY_TEMPLATECODE = "IMG22013";
    private final String BOOKING_SUCCESS_TEMPLATECODE = "IMG22014";
    private final String DIAGNOSE_SUCCESS_TEMPLATECODE_DOCTOR = "TMP22023";
    private final String DIAGNOSE_SUCCESS_TEMPLATECODE_USER = "TMP22022";

    private final String DIAGNOSE_MSG_DOCTOR_APP_CODE = "yytb294d158a26b11e6";

    @Autowired
    private ExtensionDao extensionDao;

    public ResponseObject sendBoneMsgCancelOrder(String data){
        logger.info("[BoneMsgServiceImpl.sendBoneMsgCancelOrder json-->]" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        try{
            JSONObject request = JSONObject.parseObject(data);
            String orderNo = request.getString("order_no");
            String templateCode = "36002";
            String firstMsg = "您好，您提交的订单已被取消。若有支付费用，将在1-3个工作日内原渠道退还。";
            String remark = "温馨提示：若有相关疑问，可联系客服电话020-85600747";

            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no", orderNo);
            Response ordResponse = BoneService.callUnderlineFromInternal("",
                    "yyt.bone.order.get", JsonUtils.toJsonString(ordQueryMap));
            logger.info("sendBoneMsg, yyt.bone.order.get ordResponse="+ JSON.toJSONString(ordResponse));
            if(!"0".equals(ordResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001", "查询订单失败。");
                return responseObject;
            }
            JSONObject order = JSONObject.parseObject(ordResponse.getResult());
            /**根据订单好查出订单对象 end****************/
            String orderTypeName = "";
            String typeFlag = "";

            if (order.getString("order_type") !=null &&order.getString("order_type").equals("91")){
                orderTypeName ="问诊";
                typeFlag = "1";
            }else if(order.getString("order_type") !=null &&(order.getString("order_type").equals("93")||order.getString("order_type").equals("92"))){
                orderTypeName ="手术预约";
                typeFlag = "2";
            }
            String platform_type="";
            if ("1".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))) {
                platform_type="1";
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))){
                platform_type="2";
            }

            //根据订单状态获取跳转链接
            String actionUrl = "";
            if("1".equals(typeFlag)){
                actionUrl = BoneMsgUtils.getActionUrl(CANCEL_INQUIRY_TEMPLATECODE) + order.getString("order_no")+ "&app_code=" + order.getString("platform_org_app_code");
            }else{
                actionUrl = BoneMsgUtils.getActionUrl(CANCEL_OPERATION_TEMPLATECODE) + order.getString("order_no") + "&app_code=" + order.getString("platform_org_app_code");
            }


            String method = "yyt.message.msg.template.send";
            String messageContent = "{\"user_type\":\"2\",\"order_no\":\"" + order.getString("order_no")
                    + "\",\"platform_type\":\"" + platform_type + "\",\"org_app_code\":\"" + order.getString("platform_org_app_code") +  "\",\"org_code\":\"" + order.getString("org_code") + "\",\"to_user\":\""
                    + order.getString("open_id")
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl +
                    "\",\"msg_content\":\"{\\\"first\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"keyword1\\\": \\\""
                    + order.getString("user_name")
                    + "\\\",\\\"keyword2\\\": \\\""
                    + order.getString("appointment_doctor_name")
                    + "\\\",\\\"keyword3\\\": \\\""
                    + order.getString("order_no")
                    + "\\\",\\\"keyword4\\\": \\\""
                    + order.getString("update_time")
                    + "\\\",\\\"keyword5\\\": \\\""
                    +orderTypeName
                    + "\\\",\\\"remark\\\": \\\"" +
                    remark
                    + "\\\"}\"}";
            logger.info("sendBoneMsgCancelOrder ->yyt.message.msg.template.send消息推送入参："+JSON.toJSONString(messageContent));
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("sendBoneMsgCancelOrder ->yyt.message.msg.template.send消息推送出参："+JSON.toJSONString(messageResponse));
            if (!"0".equals(messageResponse.getResultCode())){
                logger.info("sendBoneMsgCancelOrder  发送取消订单消息失败");
                responseObject.setResultCodeAndMessage("1001","发送取消订单消息失败");
            }else {
                logger.info("sendBoneMsgCancelOrder  发送取消订单消息成功");
                responseObject.setResultCodeAndMessage("0","发送取消订单消息成功");
            }

        }catch (Exception e){
            logger.error("发送骨科消息失败",e);
            responseObject.setResultCodeAndMessage("-1","发送骨科消息失败");
            return responseObject;
        }
        return responseObject;
    }


    public ResponseObject sendBoneMsgSuccessOrder(String data){
        logger.info("[BoneMsgServiceImpl.sendBoneMsgSuccessOrder问诊/押金单支付成功向患者发送消息入参-->]" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        Extension extension = new Extension();
        try{
            JSONObject request = JSONObject.parseObject(data);
            String orderNo = request.getString("order_no");
            String appId = request.getString("app_id");
            String openId = request.getString("open_id");
            String templateCode = "36001";
            String remark = "温馨提示：若有相关疑问，可联系客服电话020-85600747。";

            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no", orderNo);
            Response ordResponse = BoneService.callUnderlineFromInternal("",
                    "yyt.bone.order.get", JsonUtils.toJsonString(ordQueryMap));
            logger.info("问诊/押金单支付成功,订单号:"+orderNo+",yyt.bone.order.get ordResponse="+ JSON.toJSONString(ordResponse));
            if(!"0".equals(ordResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001", "查询订单失败。");
                return responseObject;
            }
            JSONObject order = JSONObject.parseObject(ordResponse.getResult());
            /**根据订单好查出订单对象 end****************/

            String orderTypeName = "";
            String typeFlag = "";

            if (order.getString("order_type") !=null &&order.getString("order_type").equals("91")){
                orderTypeName ="问诊";
                typeFlag = "1";
            }else if(order.getString("order_type") !=null &&(order.getString("order_type").equals("93")||order.getString("order_type").equals("92"))){
                orderTypeName ="手术预约";
                typeFlag = "2";
            }
            String firstMsg = "您好,"+order.getString("user_name")+",您已成功提交"+orderTypeName+"订单。平台将在1-3个工作日内告知您专家的反馈结果。";
            String platform_type="";
            if ("1".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))) {
                platform_type="1";
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))){
                platform_type="2";
            }

            logger.debug("患者支付押金单/问诊单发起推送消息->获取发送用户信息sendBoneMsgSuccessOrder->request:userId="+order.getString("user_id")+",appId="+appId);
            PersonalUserOpenid personalUserOpenid = BaseService.getBaseClient().getPersonalUserOpenid(order.getString("user_id"), appId,null);
            logger.debug("患者支付押金单/问诊单发起推送消息->获取发送用户信息sendBoneMsgSuccessOrder->response:"+JsonUtils.toJsonString(personalUserOpenid));
            if (personalUserOpenid == null) {
                throw new CallException(ErrorCodeDefine.MESSAGE_NOT_FIND_OPENID, "找不到应用账号");
            }

            //根据订单状态获取跳转链接
            String actionUrl = "";
            if("1".equals(typeFlag)){
                actionUrl = BoneMsgUtils.getActionUrl(CANCEL_INQUIRY_TEMPLATECODE) + order.getString("order_no")+ "&app_code=" + personalUserOpenid.getAppCode();
            }else{
                actionUrl = BoneMsgUtils.getActionUrl(CANCEL_OPERATION_TEMPLATECODE) + order.getString("order_no") + "&app_code=" + personalUserOpenid.getAppCode();
            }

            String method = "yyt.message.msg.template.send";
            String messageContent = "{\"user_type\":\"2\",\"order_no\":\"" + order.getString("order_no")
                    + "\",\"platform_type\":\"1\",\"org_app_code\":\"" + personalUserOpenid.getAppCode() +  "\",\"org_code\":\"" + order.getString("org_code") + "\",\"to_user\":\""
                    + openId
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl
                    + "\",\"msg_content\":\"{\\\"first\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"keyword1\\\": \\\""
                    + order.getString("user_name")
                    + "\\\",\\\"keyword2\\\": \\\""
                    + order.getString("appointment_doctor_name")
                    + "\\\",\\\"keyword3\\\": \\\""
                    + order.getString("order_no")
                    + "\\\",\\\"keyword4\\\": \\\""
                    + order.getString("update_time")
                    + "\\\",\\\"keyword5\\\": \\\""
                    +orderTypeName
                    + "\\\",\\\"remark\\\": \\\"" +
                    remark
                    + "\\\"}\"}";
            logger.info("问诊/押金单支付成功,订单号:"+orderNo+",患者端发送消息模板入参"+ messageContent);
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("问诊/押金单支付成功,订单号:"+orderNo+",患者端发送消息模板出参"+ JSON.toJSONString(messageResponse));
            //记录医患关系
            extension.setOrgUserId(order.getString("appointment_doctor_id"));
            extension.setPersonalUserId(order.getString("user_id"));
            List<Extension> voOrderList = extensionDao.select(extension);
            if (voOrderList.size() < 1) {
                extension.setId(PKGenerator.generateId());
                extension.setPersonalOpenId(openId);
                extension.setPayMode((short) 1);
                extension.setDefaultFlag((short) 1);
                extension.setCreatedTime(simpleDateFormat.format(new Date()));
                extension.setUpdateTime(simpleDateFormat.format(new Date()));
                extensionDao.insert(extension);
            }
            if (!"0".equals(messageResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001","发送预约订单消息失败|未发送主治订单处理通知");
                logger.info("sendBoneMsgSuccessOrder问诊/押金单支付成功,发送预约订单消息失败");
            }else {
             /*   responseObject.setResultCodeAndMessage("0","发送预约订单消息成功|不发送主治订单处理通知");
                logger.info("sendBoneMsgSuccessOrder问诊/押金单支付成功,发送预约订单消息成功");

                //主治订单处理通知
                String professorDoctorId = order.getString("professor_doctor_id");
                String appointmentDoctorId=order.getString("appointment_doctor_id");
                String type=null;
                logger.info("问诊/押金单支付成功,sendBoneMsgSuccessOrder->professorDoctorId:"+professorDoctorId+",appointmentDoctorId:"+appointmentDoctorId);
                if(!StringUtils.isNullOrBlank(professorDoctorId)||!StringUtils.isNullOrBlank(appointmentDoctorId)){
                    OrgUserOpenidVo openidVo = new OrgUserOpenidVo();
                    if(!StringUtils.isNullOrBlank(professorDoctorId)){
                        openidVo.setOrgUserId(professorDoctorId);
                        type="1";
                    }else if(!StringUtils.isNullOrBlank(appointmentDoctorId)){
                        openidVo.setOrgUserId(appointmentDoctorId);
                        type="2";
                    }
                    logger.info("系统帐号和公众号/服务窗对应关系sendBoneMsgSuccessOrder->request:"+JSON.toJSONString(openidVo));
                    Response response = BaseService.callUnderlineFromInternal("yyt.base.orgopenid.get", JsonUtils.toJsonString(openidVo));
                    logger.info("系统帐号和公众号/服务窗对应关系sendBoneMsgSuccessOrder->response->"+JSON.toJSONString(response));
                    if("0".equals(response.getResultCode())){
                        List<OrgUserOpenidVo> orgUserOpenidVos = JsonUtils.parseArray(response.getResult(), OrgUserOpenidVo.class);
                        OrgUserOpenidVo orgUserOpenidVo = orgUserOpenidVos.get(0);
                        BoneMessageRequestVo requestVo = new BoneMessageRequestVo();
                        requestVo.setAppId(orgUserOpenidVo.getAppId());
                        requestVo.setOrderNo(order.getString("order_no"));
                        requestVo.setSendOpenId(orgUserOpenidVo.getOpenId());
                        requestVo.setSendAppCode(orgUserOpenidVo.getAppCode());
                        requestVo.setTemplateCode("36005");
                        requestVo.setType(type);
                        ResponseObject boneReps = boneService.sendBoneMessage(JsonUtils.toJsonString(requestVo));
                        if (!"0".equals(boneReps.getResultCode())){
                            logger.info("sendBoneMsgSuccessOrder  发送主治订单处理通知失败,"+"Code:"+boneReps.getResultCode()+",Message:"+boneReps.getResultMessage());
                            responseObject.setResultCodeAndMessage("1001","发送预约订单消息成功|发送主治订单处理通知失败");
                        }else {
                            logger.info("发送主治订单处理通知成功 message:" + boneReps.getResultMessage());
                            responseObject.setResultCodeAndMessage("0","发送预约订单消息成功|发送主治订单处理通知成功");
                        }
                    }
                }*/
            }

        }catch (Exception e){
            logger.error("发送预约订单消息失败",e);
            responseObject.setResultCodeAndMessage("-1","发送预约订单消息失败");
            return responseObject;
        }
        return responseObject;

    }


    public ResponseObject sendBoneMsgSurgeryArrangeOrder(String data){
        logger.info("手术单支付成功[BoneMsgServiceImpl.sendBoneMsgSurgeryArrangeOrder json-->]" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        try{
            JSONObject request = JSONObject.parseObject(data);
            String orderNo = request.getString("order_no");
            String appId = request.getString("app_id");
            String openId = request.getString("open_id");
            String templateCode = "36003";
            String remark = "温馨提示：若有相关疑问，可联系客服电话020-85600747。";

            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no", orderNo);
            Response ordResponse = BoneService.callUnderlineFromInternal("",
                    "yyt.bone.order.get", JsonUtils.toJsonString(ordQueryMap));
            logger.info("sendBoneMsg, yyt.bone.order.get ordResponse="+ JSON.toJSONString(ordResponse));
            if(!"0".equals(ordResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001", "查询订单失败。");
                return responseObject;
            }
            JSONObject order = JSONObject.parseObject(ordResponse.getResult());
            /**根据订单好查出订单对象 end****************/
            String platform_type="";
            if ("1".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))) {
                platform_type="1";
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))){
                platform_type="2";
            }
            String firstMsg = "您好,"+order.getString("user_name")+",您已成功支付手术费用。将尽快安排手术相关事宜并与您沟通。";

            logger.debug("患者支付手术单发起推送消息->获取发送用户信息sendBoneMsgSuccessOrder->request:userId="+order.getString("user_id")+",appId="+appId);
            PersonalUserOpenid personalUserOpenid = BaseService.getBaseClient().getPersonalUserOpenid(order.getString("user_id"), appId,null);
            logger.debug("患者支付手术单发起推送消息->获取发送用户信息sendBoneMsgSuccessOrder->response:"+JsonUtils.toJsonString(personalUserOpenid));
            if (personalUserOpenid == null) {
                throw new CallException(ErrorCodeDefine.MESSAGE_NOT_FIND_OPENID, "找不到应用账号");
            }

            String actionUrl = BoneMsgUtils.getActionUrl(BOOKING_SUCCESS_TEMPLATECODE) + order.getString("order_no") + "&app_code=" + personalUserOpenid.getAppCode();

            String method = "yyt.message.msg.template.send";
            String messageContent = "{\"user_type\":\"2\",\"order_no\":\"" + order.getString("order_no")
                    + "\",\"platform_type\":\"" + platform_type + "\",\"org_app_code\":\"" + personalUserOpenid.getAppCode() +  "\",\"org_code\":\"" + order.getString("org_code") + "\",\"to_user\":\""
                    + openId
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl
                    + "\",\"msg_content\":\"{\\\"first\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"keyword1\\\": \\\""
                    + order.getString("user_name")
                    + "\\\",\\\"keyword2\\\": \\\""
                    + order.getString("appointment_doctor_name")
                    + "\\\",\\\"keyword3\\\": \\\""
                    + order.getString("professor_doctor_name")
                    + "\\\",\\\"keyword4\\\": \\\""
                    + order.getString("update_time")
                    + "\\\",\\\"keyword5\\\": \\\""
                    + "手术预约"
                    + "\\\",\\\"remark\\\": \\\"" +
                    remark
                    + "\\\"}\"}";
            logger.info("手术单支付成功[BoneMsgServiceImpl.sendBoneMsgSurgeryArrangeOrder发送消息模板入参] " + messageContent);
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("手术单支付成功[BoneMsgServiceImpl.sendBoneMsgSurgeryArrangeOrder发送消息模板出参] " + JSON.toJSONString(messageResponse));
            if (!"0".equals(messageResponse.getResultCode())){
                logger.info("sendBoneMsgSurgeryArrangeOrder  发送手术支付预约订单消息失败");
                responseObject.setResultCodeAndMessage("1001","发送预约订单消息失败");
            }else {
                logger.info("sendBoneMsgSurgeryArrangeOrder  发送手术支付订单消息成功");
                responseObject.setResultCodeAndMessage("0","发送预约订单消息成功");
            }

        }catch (Exception e){
            logger.error("发送预约订单消息失败",e);
            responseObject.setResultCodeAndMessage("-1","发送预约订单消息失败");
            return responseObject;
        }
        return responseObject;

    }

    /**
     * 面诊订单支付成功消息推送——患者
     * @param data
     * @return
     */
    public ResponseObject sendBoneMsgDiagnoseOrderToUser(String data){
        logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgSurgeryArrangeOrder json-->]" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        try {

            JSONObject request = JSONObject.parseObject(data);
            String orderNo = request.getString("order_no");
            String templateCode = "22022";
            String remark = "温馨提示：若有相关疑问，可联系客服电话020-85600747。";

            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no", orderNo);
            Response ordResponse = BoneService.callUnderlineFromInternal("",
                    "yyt.bone.order.get", JsonUtils.toJsonString(ordQueryMap));
            logger.info("sendBoneMsg, yyt.bone.order.get ordResponse="+ JSON.toJSONString(ordResponse));
            if(!"0".equals(ordResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001", "查询订单失败。");
                return responseObject;
            }
            JSONObject order = JSONObject.parseObject(ordResponse.getResult());
            /**根据订单好查出订单对象 end****************/
            String platform_type="";
            if ("1".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))) {
                platform_type="1";
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))){
                platform_type="1";
            }

            String firstMsg ="您好,"+order.getString("user_name")+",您已成功提交VIP预约订单,请按照预约时间前往就诊地址就诊,谢谢！。";
            //根据订单状态获取跳转链接
            String actionUrl = BoneMsgUtils.queryActionUrl(DIAGNOSE_SUCCESS_TEMPLATECODE_USER) + order.getString("order_no") + "&app_code=" + order.getString("platform_org_app_code");

            String method = "yyt.message.msg.template.send";

            String messageContent = "{\"user_type\":\"2\",\"order_no\":\"" + order.getString("order_no")
                    + "\",\"platform_type\":\"" + platform_type + "\",\"org_app_code\":\"" + order.getString("platform_org_app_code") +  "\",\"org_code\":\"" + order.getString("org_code") + "\",\"to_user\":\""
                    + order.getString("open_id")
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl
                    + "\",\"msg_content\":\"{\\\"title\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"userName\\\": \\\""
                    + order.getString("user_name")
                    + "\\\",\\\"doctorName\\\": \\\""
                    + order.getString("appointment_doctor_name")
                    + "\\\",\\\"scheduleTime\\\": \\\""
                    + order.getString("schedule_time")
                    + "\\\",\\\"address\\\": \\\""
                    + order.getString("user_address")
                    + "\\\",\\\"reserveNo\\\": \\\""
                    + order.get("reserve_no")
                    + "\\\",\\\"remark\\\": \\\"" +
                    remark
                    + "\\\"}\"}";

            logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgDiagnoseOrder发送消息模板入参] " + messageContent);
            Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
            logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgDiagnoseOrder发送消息模板出参] " + JSON.toJSONString(messageResponse));
            if ("0".equals(messageResponse.getResultCode()) ){
                logger.info("sendBoneMsgDiagnoseOrder  发送手术支付订单消息成功");
                responseObject.setResultCodeAndMessage("0","发送预约订单消息成功");
            }else {
                responseObject.setResultCodeAndMessage("1001","发送面诊订单支付消息失败");
                logger.info("sendBoneMsgDiagnoseOrder  发送面诊订单支付消息失败");
            }
        }catch (Exception e){
            logger.error("发送面诊订单支付消息失败",e);
            responseObject.setResultCodeAndMessage("-1","发送面诊订单支付消息失败");
            return responseObject;
        }
        return  responseObject;
    }

    /**
     * 面诊订单支付成功消息推送——专家
     * @param data
     * @return
     */
    public ResponseObject sendBoneMsgDiagnoseOrderToDoctor(String data) {
        logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgSurgeryArrangeOrder json-->]" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        Extension extension = new Extension();
        try {
            JSONObject request = JSONObject.parseObject(data);
            String orderNo = request.getString("order_no");
            String templateCode = "22023";
            String remark = "温馨提示：看诊结束后记得向患者询问预约号，并点击该消息，然后点击订单完成，填写该预约号。若有相关疑问，可联系客服电话020-85600747。";

            /**根据订单好查出订单对象**/
            Map<String, String> ordQueryMap = new HashMap<String, String>();
            ordQueryMap.put("order_no", orderNo);
            Response ordResponse = BoneService.callUnderlineFromInternal("",
                    "yyt.bone.order.get", JsonUtils.toJsonString(ordQueryMap));
            logger.info("sendBoneMsg, yyt.bone.order.get ordResponse="+ JSON.toJSONString(ordResponse));
            if(!"0".equals(ordResponse.getResultCode())){
                responseObject.setResultCodeAndMessage("1001", "查询订单失败。");
                return responseObject;
            }
            JSONObject order = JSONObject.parseObject(ordResponse.getResult());
            /**根据订单好查出订单对象 end****************/
            String platform_type="";
            if ("1".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))) {
                platform_type="1";
            }else if("2".equals(String.valueOf(Integer.valueOf(order.getString("pay_mode"))/10%10))){
                platform_type="1";
            }

            String firstMsg ="您好,"+order.getString("appointment_doctor_name")+"医生,有患者预约了您的专家会诊,请按照预约时间和地址给患者看诊,谢谢！。";
//            String appCode =DIAGNOSE_MSG_DOCTOR_APP_CODE;
            //根据订单状态获取跳转链接
            String actionUrl = BoneMsgUtils.queryActionUrl(DIAGNOSE_SUCCESS_TEMPLATECODE_DOCTOR) + order.getString("order_no") + "&app_code=" + DIAGNOSE_MSG_DOCTOR_APP_CODE;

            String method = "yyt.message.msg.template.send";

            //获取医生信息
            /****根据医生id 获取医生的appid ****/
            String doctorId = order.getString("appointment_doctor_id");
            Map<String,Object> map = new HashMap<>();
            map.put("org_user_id",doctorId);
            map.put("app_code",DIAGNOSE_MSG_DOCTOR_APP_CODE);
            Response rep = BaseService.callHumpFromInternal("yyt.base.orgopenid.get",JsonUtils.toJsonString(map));
            List<OrgUserOpenidVo> list = JSON.parseArray(rep.getResult(),OrgUserOpenidVo.class);
            OrgUserOpenidVo vo = list.get(0);

            String messageContentDoctor ="{\"user_type\":\"2\",\"order_no\":\"" + order.getString("order_no")
                    + "\",\"platform_type\":\"" + platform_type + "\",\"org_app_code\":\"" + vo.getAppCode() +  "\",\"to_user\":\""
                    + vo.getOpenId()
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl
                    + "\",\"msg_content\":\"{\\\"title\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"userName\\\": \\\""
                    + order.getString("user_name")
                    + "\\\",\\\"doctorName\\\": \\\""
                    + order.getString("appointment_doctor_name")
                    + "\\\",\\\"scheduleTime\\\": \\\""
                    + order.getString("schedule_time")
                    + "\\\",\\\"address\\\": \\\""
                    + order.getString("user_address")
                    + "\\\",\\\"orderTypeName\\\": \\\""
                    + "专家会诊订单"
                    + "\\\",\\\"remark\\\": \\\"" +
                    remark
                    + "\\\"}\"}";
            logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgDiagnoseOrder发送消息模板入参] " + messageContentDoctor);
            Response messageRep = MessageService.callHumpFromInternal(method, messageContentDoctor);
            logger.info("面诊订单支付成功[BoneMsgServiceImpl.sendBoneMsgDiagnoseOrder发送消息模板出参数] " + JsonUtils.toJsonString(messageRep));
            if ("0".equals(messageRep.getResultCode()) ){
                logger.info("sendBoneMsgDiagnoseOrderToDoctor  发送手术支付订单消息（医生端）成功");
                responseObject.setResultCodeAndMessage("0","发送预约订单消息（医生端）成功");
            }else {
                responseObject.setResultCodeAndMessage("1001","发送面诊订单支付消息（医生端）失败");
                logger.info("sendBoneMsgDiagnoseOrderToDoctor  发送面诊订单支付消息（医生端）失败");
            }

            //记录医患关系
            extension.setOrgUserId(order.getString("appointment_doctor_id"));
            extension.setPersonalUserId(order.getString("user_id"));
            List<Extension> voOrderList = extensionDao.select(extension);
            if (voOrderList.size() < 1) {
                extension.setId(PKGenerator.generateId());
                extension.setPersonalOpenId(order.getString("open_id"));
                extension.setPayMode((short) 1);
                extension.setDefaultFlag((short) 1);
                extension.setCreatedTime(simpleDateFormat.format(new Date()));
                extension.setUpdateTime(simpleDateFormat.format(new Date()));
                extensionDao.insert(extension);
            }
        } catch (Exception e) {
            logger.error("发送面诊订单支付消息失败", e);
            responseObject.setResultCodeAndMessage("-1", "发送面诊订单支付消息失败");
            return responseObject;
        }
        return responseObject;
    }
}
